using System.Text.RegularExpressions;

namespace AdminSG3L.Applicaticn.Utils;

public static partial class FormValidator
{
    public static string? ValidateUsername(string? username)
    {
        if (string.IsNullOrWhiteSpace(username))
            return "用户名不能为空";
        username = username.Trim();
        if (username.Length < 3 || username.Length > 20)
            return "用户名长度应为3-20个字符";
        if (!MyRegex().IsMatch(username))
            return "用户名只能包含字母、数字、下划线和中文";
        return null;
    }

    public static string? ValidateCaptcha(string? captcha, string? expectedCaptcha)
    {
        if (string.IsNullOrWhiteSpace(captcha))
            return "图形验证码不能为空";
        if (string.IsNullOrWhiteSpace(expectedCaptcha))
            return "图形验证码已过期，请刷新";
        if (!captcha.Trim().Equals(expectedCaptcha.Trim(), StringComparison.OrdinalIgnoreCase))
            return "图形验证码错误";
        return null;
    }

    public static string? ValidatePassword(string? password)
    {
        if (string.IsNullOrWhiteSpace(password))
            return "密码不能为空";
        if (password.Length < 6 || password.Length > 20)
            return "密码长度应为6-20位";
        if (!Regex.IsMatch(password, @"^(?=.*[a-zA-Z])(?=.*\d)"))
            return "密码必须包含字母和数字";
        return null;
    }

    public static string? ValidateConfirmPassword(string? password, string? confirmPassword)
    {
        if (string.IsNullOrWhiteSpace(confirmPassword))
            return "确认密码不能为空";
        if (password != confirmPassword)
            return "两次输入的密码不一致";
        return null;
    }

    public static string? ValidateAgreement(bool? agreement)
    {
        if (!agreement.HasValue || !agreement.Value)
            return "请阅读并同意用户协议和隐私政策";
        return null;
    }

    public static string? ValidateEmail(string? email)
    {
        if (string.IsNullOrWhiteSpace(email))
            return "邮箱不能为空";
        email = email.Trim();
        if (!MyRegex4().IsMatch(email))
            return "请输入正确的邮箱地址";
        return null;
    }

    public static string? ValidateEmailCode(string? emailCode, string? email)
    {
        if (string.IsNullOrWhiteSpace(emailCode))
            return "验证码不能为空";
        emailCode = emailCode.Trim();
        if (!MyRegex3().IsMatch(emailCode))
            return "请输入6位数字验证码";
        if (!string.IsNullOrWhiteSpace(email) && email.Trim().StartsWith("test@") && emailCode != "123456")
            return "测试邮箱验证码为：123456";
        return null;
    }

    [GeneratedRegex(@"^[a-zA-Z0-9_\u4e00-\u9fa5]+$")]
    private static partial Regex MyRegex();
    [GeneratedRegex(@"^\d{6}$")]
    private static partial Regex MyRegex3();
    [GeneratedRegex(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$")]
    private static partial Regex MyRegex4();
} 